//
//  SearchViewController.m
//  myCar
//
//  Created by 刘莉 on 14-11-4.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "WebColor.h"
#import "PopoverView.h"
#import "Car.h"
#import "Base.h"
#import "HttpViewController.h"
#import "ForumDetailController.h"
#import "AFNetworking.h"
#import "ExaxtCar.h"
#import "MBProgressHUD.h"
@interface SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate >
@property (nonatomic ,retain) NSMutableArray *searchArray;
@property (nonatomic ,retain) UISearchBar *searchBar;
@property (nonatomic ,retain) UITableView *tableView;
@property (nonatomic ,retain) NSMutableArray *showArray;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) NSString *url;
@property (nonatomic, retain) NSArray *array;
@property (nonatomic, assign) NSInteger index;
@end

@implementation SearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.searchArray = [NSMutableArray array];
        self.showArray   = [NSMutableArray array];
        self.array       = [NSArray   array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"搜索";
    [self localToken];
    [self setupSubViews];
}
- (void)setupSubViews
{
    
    self.button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.button.frame = CGRectMake(0, 0, 80, 60);
    [self.button setTitle:@"找车" forState:(UIControlStateNormal)];
    [self.view addSubview:self.button];
    [self.button addTarget:self action:@selector(buttonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    self.button.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    self.button.imageEdgeInsets = UIEdgeInsetsMake(0, 40, 0, 0);
    self.button.backgroundColor = [WebColor silver];
    self.button.layer.borderColor = [WebColor gray].CGColor;
    self.button.layer.borderWidth = 0.5;
    
    [self.button setImage:[UIImage imageNamed:@"xiangxia.png"] forState:(UIControlStateNormal)];
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(80, 0,self.view.bounds.size.width - 80, 60)];
    
    self.searchBar.placeholder = @"Search";
    self.searchBar.delegate = self;
    self.searchBar.barTintColor = [WebColor silver];
    [self.view addSubview:self.searchBar];
    [_searchBar release];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, self.view.bounds.size.width, self.view.bounds.size.height - 64 - 60 - 49) style:(UITableViewStylePlain)];
    // 设置cell无下划线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
}

#pragma mark tableView协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.showArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"search"]autorelease];
    }
    Base *base = self.showArray[indexPath.row];
    cell.textLabel.text = base.name;
    if (self.index == 1) {
        cell.detailTextLabel.text = @"进入论坛";
        cell.detailTextLabel.font = [ UIFont systemFontOfSize:14];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

- (void)buttonClicked:(UIButton *)button
{
    [button setImage:[UIImage imageNamed:@"xiangshang.png"] forState:(UIControlStateNormal)];
    CGPoint point = CGPointMake(0, button.frame.origin.y + button.frame.size.height + 64);
    NSArray *titles = @[@"找车", @"找论坛"];
        PopoverView *pop = [[PopoverView alloc] initWithPoint:point titles:titles images:nil];
    pop.selectRowAtIndex = ^(NSInteger index){
        self.index = index;
        if (index == 1) {
            self.array = [self localToken];
        }
        [button setTitle:titles[index] forState:(UIControlStateNormal)];
        [button setImage:[UIImage imageNamed:@"xiangxia.png"] forState:(UIControlStateNormal)];
    };
    
    [pop show];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.searchArray removeAllObjects];
    [self.showArray  removeAllObjects];
    if (self.index == 0) {
        [self netConnectionWithString:searchText];
    }
    for (Base *base in self.array) {
        if ([base.name hasPrefix:searchText]) {
            [self.searchArray addObject:base];
        }
        if ([base.name hasSuffix:searchText] && ![base.name hasPrefix:searchText]) {
            [self.searchArray addObject:base];
        }
        if (![base.name hasSuffix:searchText] && ![base.name hasPrefix:searchText] && [base.name rangeOfString:searchText].location != NSNotFound) {
            [self.searchArray addObject:base];
        }
    }
    
   [self.showArray addObjectsFromArray:self.searchArray];
    [self.tableView reloadData];
}
- (void)netConnectionWithString:(NSString *)str
{
    //@"http://mrobot.pcauto.com.cn/v2/cms/channels/55555?pageNo=%d&pageSize=20&pro=%@&city=%@&v=4.0.0
    MBProgressHUD *hub = [[MBProgressHUD alloc] init];
    [hub setMode:MBProgressHUDModeIndeterminate];
    [hub show:YES];
    [self.view addSubview:hub];
    NSString *url = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/models/search"];
    NSDictionary *dic = @{@"keyword":str, @"pageNo":@"1", @"orderId":@"1"};
    
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager1 GET:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *arr = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in arr) {
            Base *base = [[Base alloc]initWithDictionary:dic];
            [self.searchArray addObject:base];
            [base release];
            NSLog(@"%@", base.name);
            [self.showArray addObjectsFromArray:self.searchArray];
        }
        [self.tableView reloadData];
        [hub removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请检查网络配置" delegate:self cancelButtonTitle:@"请返回" otherButtonTitles:nil, nil];
        [alertView show];
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"noNet.jpg"];
        self.tableView.backgroundView = imageView;
        [imageView release];
    }];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSArray *)localToken
{
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *arrPath = [cachesPath stringByAppendingPathComponent:@"Forum.plist"];
    NSArray *arrBack = [NSKeyedUnarchiver unarchiveObjectWithFile:arrPath];
    return arrBack;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Base *base = [self.showArray objectAtIndex:indexPath.row];
    [self setBackItem:base.name];
    if (self.index == 0) {
        HttpViewController *httpVC = [[HttpViewController alloc]init];
        httpVC.idStr = [NSString stringWithFormat:@"http://price.pcauto.com.cn/sg%@/", base.idNum];
        ExaxtCar *car = [[ExaxtCar alloc]init];
        car.serialName = base.name;
        car.idNum = base.idNum;
        httpVC.car = car;
        [car release];
        [self.navigationController pushViewController:httpVC animated:YES];
        [httpVC release];
    } else {
        ForumDetailController *forumVC = [[ForumDetailController alloc]init];
        forumVC.base = base;
        [self.navigationController pushViewController:forumVC animated:YES];
        [forumVC release];
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchArray removeAllObjects];
    [self.tableView reloadData];
    [self.view endEditing:YES];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchArray removeAllObjects];
    [self.showArray  removeAllObjects];
    [self.tableView reloadData];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchBar resignFirstResponder];
}

- (void)setBackItem:(NSString *)str
{
    UIBarButtonItem *backItem = [[[UIBarButtonItem alloc] init] autorelease];
    backItem.title = str;
    backItem.tintColor = [UIColor whiteColor];
    self.navigationItem.backBarButtonItem = backItem;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
